package com.example.segment_saver;


import java.io.File;

import android.annotation.TargetApi;
import android.app.Fragment;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class SiteDetailFragment  extends Fragment{

	
	private SiteList sites = new SiteList();
	private String Url;
	private boolean saveData = true;
	
	public void onCreate (Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
		
		Url = getActivity().getIntent().getStringExtra("Url"); //todo might be the problem
	}
	public void onResume()
	{
		super.onResume();
		saveData = true;
		sites.load(new File(getActivity().getFilesDir(), "sites.bin"));
		
		if(Url != null)
		{
			SiteData data = sites.getSite(Url);
			
			EditText site = (EditText) getActivity().findViewById(R.id.Url_name);
			
			site.setText(data.getUrl());
			
			
		}
	}
	
	public void onPause()
	{
		super.onPause();
		if(saveData)
		{
			SiteData data = null;
			
			EditText site = (EditText) getActivity().findViewById(R.id.Url_name);
			
			String site_url = site.getText().toString();
			
			if(Url != null)
			{
				sites.removeSite(Url);
			}
			
			Url = site_url;
			
			data = new SiteData(site_url);
			
			sites.addSite(Url, data);
			
			sites.save(new File(getActivity().getFilesDir(), "sites.bin"));
			
		}
	}
	
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState )
	{
		return inflater.inflate(R.layout.fragment_add_site, container, false);
	}
	
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
	{
		inflater.inflate(R.menu.fragment_delete_site, menu);
	}
	
	public boolean onOptionsItemSelected (MenuItem item)
	{
		if(item.getItemId() == R.id.menu_delete_site)
		{
			saveData = true;
		}
		else if(item.getItemId() == R.id.menu_cancel)
		{
			saveData = false;
		}
		getActivity().finish();
		return true;
	}
	
}
